import logging
from typing import Any, Dict, Optional
from django.conf import settings
import requests

logger = logging.getLogger(__name__)

class LLMClient:
	"""Unified LLM client. Prefers remote API when AI_API_KEY is configured.
	invoke(prompt: str) -> str
	"""
	def __init__(self, local_llm: Optional[Any] = None) -> None:
		self.local_llm = local_llm
		self.api_url = getattr(settings, 'AI_API_URL', 'https://api.deepseek.com/v1/chat/completions')
		self.api_key = getattr(settings, 'AI_API_KEY', '')
		self.model_name = getattr(settings, 'AI_MODEL_NAME', 'deepseek-chat')

	def invoke(self, prompt: str, temperature: float = 0.3, max_tokens: int = 1024) -> str:
		"""Call remote API when api_key present; otherwise try local_llm; else raise."""
		# When API key is configured, always use remote API and do NOT fall back to local
		if self.api_key:
			try:
				headers = {
					'Authorization': f'Bearer {self.api_key}',
					'Content-Type': 'application/json'
				}
				data = {
					"model": self.model_name,
					"messages": [
						{"role": "user", "content": prompt}
					],
					"temperature": temperature,
					"max_tokens": max_tokens,
				}
				resp = requests.post(self.api_url, headers=headers, json=data, timeout=120)
				resp.raise_for_status()
				j = resp.json()
				return j['choices'][0]['message']['content']
			except Exception as e:
				logger.error(f"Remote LLM call failed: {e}")
				# fallthrough to local if available
		# Only attempt local fallback when there is explicitly no API key configured
		if not self.api_key and self.local_llm is not None:
			try:
				return self.local_llm.invoke(prompt)
			except Exception as e:
				logger.error(f"Local LLM call failed: {e}")
		raise RuntimeError("No available LLM backend. Configure AI_API_KEY or provide local_llm.")
